/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pfc.generacion;

import java.util.ArrayList;
import org.apache.commons.lang.StringUtils;
import org.apache.ddlutils.model.Database;
import pfc.comun.Proyecto;
import pfc.modelocg.CGForm;
import pfc.modelocg.CGModel;
import pfc.modeloer.ERAttrib;
import pfc.modeloer.EREntity;
import pfc.modeloer.ERModel;

/**
 *
 * @author xandru
 */
public class GeneradorNewServlet extends GeneradorServlet {

    public GeneradorNewServlet(Proyecto pro, Database db, ERModel er, CGModel cg) {
        super(pro, db, er, cg);
    }

    void addRequest(ArrayList<String> methods, CGForm form) {
        String claseDTO = StringUtils.capitalize(form.getEntityName());
        String claseDAO = claseDTO + "DAO";
        EREntity ent = this._erModel.findEntity(form.getEntityName());

        ArrayList<String> keys = new ArrayList<String>();
        for (ERAttrib a: ent.getAttribs())
        {
            if ( (!a.isAutoIncrement()) && (!a.isGenerable()))
                keys.add(a.getName());
        }


        methods.add("protected void processRequest(HttpServletRequest request, HttpServletResponse response)");
        methods.add("throws ServletException, IOException {");
        methods.add("PrintWriter out = response.getWriter();");
        methods.add(claseDTO + " obj = new " + claseDTO + "();");
        methods.add("out.println(\"Hola mundo \" + this.getClass().getCanonicalName());");
        methods.add("String key=null;");
        methods.add("String value=null;");

        //PRUEBA VALIDACION
        methods.add("ArrayList<String> parametros = new ArrayList<String>();");
        methods.add("ArrayList<String> valores = new ArrayList<String>();");

        for (String s:keys)
        {
            methods.add("parametros.add(\"" + s + "\");");
            methods.add("valores.add(request.getParameter(\"" + s + "\"));");
        }

        methods.add("Validator val = new Validator(parametros,valores);");
        methods.add("Iterable<String> errores = val.validate(obj);");
        //methods.add("for (String err:errores)");
        //methods.add("System.out.println(err);");

        methods.add("if (errores.iterator().hasNext()) {");
        methods.add("out.println(\"Se han encontrado los siguientes errores en los datos recibidos\");");
         methods.add("for (String err:errores)");
        methods.add("out.println(err + \"<br>\");");
        methods.add("return;");
        methods.add("}");


        
        //FIN PRUEBA VALIDACION
        methods.add("try {");

        methods.add("obj = val.getValidatedObject( obj );");
        /*
        for (String s: keys)
        {
           methods.add("obj.putPropertyValue(\"" + s +"\", request.getParameter(\"" + s + "\"));");
        }
*/


        //methods.add("for (Enumeration e = request.getParameterNames();e.hasMoreElements();) {");
        //methods.add("key=(String) e.nextElement();");
        //methods.add("value = request.getParameter(key);");

//methods.add("System.out.println(\"antes de putPropertyValue \" + key + \" \" + value + \"<br>\");");
        //methods.add("obj.putPropertyValue(key,value);");
//methods.add("System.out.println(\"despues de putPropertyValue \" + key + \" \" + value + \"<br>\");");

        //methods.add("}");

        if (ent.isGenerateIdentity())
        {
            methods.add("System.out.println(\"Generando pk para " + claseDTO + "\");");
            methods.add("PrimaryKey k = " + claseDTO + "PKGen.getNewPrimaryKey();");
            methods.add("System.out.println(\"clave generada \" + k);");
            methods.add("obj.setIdentity(k);");
        }

        methods.add("}");
        methods.add("catch (Exception e) {");
        methods.add("out.println(\"Excepcion e1 \" +  e.getClass().getCanonicalName() + \": \" + e.getMessage() + \" \" + key + \"=\" + value);");
        methods.add("}");

        methods.add("try {");

        methods.add("for (PropertyDescriptor pd:PropertyUtils.getPropertyDescriptors(obj)) {");
        methods.add(" key  = pd.getName();");
        methods.add(" value = obj.stringPropertyValue(key);");
        methods.add("  out.println(key + \" = \" + value + \"<br>\");");
        methods.add("}");
        methods.add("}");
        methods.add("catch (Exception e) {");
        methods.add("out.println(\"excepcion e2 \" + key + \" \" + value + \" \" +e.getMessage());");
        methods.add("}");

        methods.add("DataSource ds = DataSourceFactory.getDataSourceFromJNDI(\"jdbc/" + this._proyecto.getNombre() + "\");");
        methods.add(claseDAO + " objDAO = new " + claseDAO + "(ds);");
        methods.add("out.println(objDAO);");
        methods.add("try {");
        methods.add("objDAO.create(obj);");
        methods.add("} catch (Exception e) {");
        methods.add("out.println(\"Excepcion creando el objeto en la base de datos\" +  e.getClass().getCanonicalName() + \": \" + e.getMessage());");
        methods.add("}");
        methods.add("}");
    }
}
